package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import util.JDBCUtil;

/**
 * Servlet implementation class ShowAllStudentServlet
 */
@WebServlet("/ShowAllStudentServlet")
public class ShowAllStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * 展示平均分
     * @see HttpServlet#HttpServlet()
     */
    public ShowAllStudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		Connection con = null;
		PreparedStatement pStatement = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "select * from study";  //从数据库获取所有学生信息
		ArrayList<Double> score = new ArrayList<Double>();
		ArrayList<String> stu = new ArrayList<String>();
		try{
			con = JDBCUtil.getConnection();
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				stu.add(rs.getString(2));
				score.add(Double.parseDouble(rs.getString(11)));
			}
			Map<String, Object> map = new HashMap<>();
			double[] allScore = new double[score.size()];
			for(int i = 0; i < score.size(); i++) {
				allScore[i] = score.get(i);
			}
			String[] stuName = new String[stu.size()];
			for(int i = 0; i < stu.size(); i++) {
				stuName[i] = stu.get(i);
			}
			map.put("allScore",allScore);
			map.put("stuName",stuName);
			response.getWriter().println(JSON.toJSONString(map));  //通过json传递学生总分和学生姓名
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.realeaseAll(rs, stmt, con, pStatement);
		}
	}

}
